import React,{useEffect,useRef,useState} from 'react'
import {useDispatch,useSelector} from "react-redux"
import * as action from "../action/index"
function Floor() {
  let dispatch = useDispatch()
  let [activeIndex,setActiveIndex] = useState(0)
let myref  =useRef(null)
  let store = useSelector(state=>({...state.shopreducer}))
  useEffect(()=>{
      console.log(1);
      dispatch(action.getfloorlist())
      setTimeout(()=>{
          window.addEventListener("scroll",handscroll,true)
      },200)
  },[])
  let handscroll = ()=>{
      let tops = myref.current.scrollTop // 获取右侧盒子的滚动距离
    //  console.dir(myref.current.children) // 将元素的子节点在控制台上格式化化一个列表，打印的东西是一个类数组
     let arr = Array.from(myref.current.children) // Array.from 是将伪数组转换为真正的数组
    //  console.log(arr)
      // 右侧大盒子滚动距离超过他的子盒子的距离顶部的距离，那么当前的子盒子对应的左侧的tab就该高亮了
      arr.forEach((item,index)=>{
          if (tops >= item.offsetTop) {
            setActiveIndex(index)
          } 
      })
  }
  let gofloor = (index)=>{
    setActiveIndex(index)
     console.log(myref.current);
     myref.current.children[index].scrollIntoView({behavior:"smooth"})
  }
  return (
    <div className='wrap'>
        <div className='left'>
            {
                store.floorarr ?. map((item,index)=>{
                    return <h4 key={index} className={`${index === activeIndex ? "active" : ""} myh4`}onClick={()=>{gofloor(index)}}>
                        {item.tit}
                    </h4>
                })
            }
        </div>
        <div className='right' ref={myref}>
            {
                   store.floorarr ?. map ((item,index)=>{
                       return <div key={index}>
                           <h4>{item.tit}</h4>
                           {
                               item.children ?.map ((ite,ind)=>{
                                   return <dl key={ind}>
                                       <dt>
                                           <img src={ite.img} alt="" />
                                       </dt>
                                       <dd>{ite.tit}</dd>
                                   </dl>
                               })
                           }
                       </div>
                   })
            }
        </div>
    </div>
  )
}

export default Floor